from machine import Pin
import utime
import network
import ntptime 
from machine import RTC
import machine
from IIC256 import *

rtc = RTC()
def sync_ntp():
    # ntptime.NTP_DELTA = 3155644800   # 可选 UTC+8偏移时间（秒），不设置就是UTC0
    # ntptime.host = 'ntp1.aliyun.com'  # 可选，ntp服务器，默认是"pool.ntp.org"

    ntptime.settime()   # 修改设备时间,到这就已经设置好了
    print("ntptime.settime()")


sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)   
#sta_if.connect("<AP_name>", "<password>") # Connect to an AP
def connectWifi():
    n=0
    if not sta_if.isconnected():
        sta_if.connect("Network_1", "15368274761")
        while not sta_if.isconnected():
            n=n+1
            print("connect...%02d"%(n))
            utime.sleep(1)
            if(n>=30):
                sta_if.active(False)
                return False
def main():
    # connectWifi()
    # n=0
    # sync_ntp()
    n=0

    while True:
        da=i2c.readfrom_mem(81,2,8)
        s=((da[0]>>4) * 10) + (da[0]&0x0f)
        m=((da[1]>>4) * 10) + (da[1]&0x0f)
        h=((da[2]>>4) * 10) + (da[2]&0x0f)
        d=((da[3]>>4) * 10) + (da[3]&0x0f)
        w=((da[4]>>4) * 10) + (da[4]&0x0f)
        mo=((da[5]>>4) * 10) + (da[5]&0x0f)
        y=((da[6]>>4) * 10) + (da[6]&0x0f)
        lprint(f"20{y:02d}-{mo:02d}-{d:02d}",70,2)
        n=n+1
        if (n>3600):
            sync_ntp()
            print(f"sync_ntp {n}")
            n=0
        t=rtc.datetime()
        print("{0:0>2d}:{1:0>2d}:{2:0>2d} {3:0>3d}".format(t[4],t[5],t[6],n))
        print(t)
        t=rtc.datetime()
        print(int(t[7]/1000))
        # utime.sleep_ms(8)
        # machine.lightsleep(1000-int(t[7]/1000))  
        utime.sleep_us(1000000-t[7])
def wake1():
    t=rtc.datetime()
    print("{0:0>2d}:{1:0>2d}:{2:0>2d} {3:0>3d}".format(t[4],t[5],t[6],n))
    print(t)
    print("dp")
    machine.deepsleep(1000)  

if __name__ == "__main__":
    main()